package com.jkj.http.sys.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jkj.http.controller.BaseController;
import com.jkj.http.entity.LayPadding;
import com.jkj.http.entity.TreeSelect;
import com.jkj.http.entity.ZTreeNode;
import com.jkj.http.interceptor.AuthorizeChecked;
import com.jkj.http.sys.entity.SysItem;
import com.jkj.http.sys.entity.SysItemsDetail;
import com.jkj.http.sys.service.SysItemService;
import com.jkj.utils.JsonUtils;
import com.jkj.utils.OperatorProvider;
import com.jkj.utils.TreeSelectHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;


@RestController
@RequestMapping(value = "/system/item")
public class ItemController extends BaseController {
    @Autowired
    private SysItemService itemService;

    /**
     * 字典列表画面
     *
     * @return
     */
    @AuthorizeChecked()
    @RequestMapping(value = "/index", method = {RequestMethod.GET})
    public ModelAndView index() {
        return new ModelAndView("system/item/index");
    }

    /**
     * 查询字典（分页）
     *
     * @param pageIndex
     * @param pageSize
     * @param keyWord
     * @return
     */
    @AuthorizeChecked()
    @RequestMapping(value = "/index", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    public String index(int pageIndex, int pageSize, String keyWord) {
        int totalCount = itemService.getTotalCount(keyWord);
        PageHelper.startPage(pageIndex, pageSize);//这行是重点，表示从pageNum页开始，每页pageSize条数据
        List<SysItem> list = itemService.getList(keyWord);
        PageInfo<SysItem> pageInfo = new PageInfo<>(list);
        List<SysItem> pageData = pageInfo.getList();
        LayPadding<SysItem> result = new LayPadding<>();
        result.setResult(true);
        result.setMsg("success");
        result.setList(pageData);
        result.setCount(totalCount);
        return JsonUtils.toJSON(result);
    }


    /**
     * 字典新增或修改页面
     *
     * @return
     */
    @AuthorizeChecked()
    @RequestMapping(value = "/form", method = {RequestMethod.GET})
    public ModelAndView form() {
        return new ModelAndView("system/item/form");
    }

    /**
     * 新增或者修改字典
     *
     * @param session
     * @param model
     * @return
     */
    @AuthorizeChecked()
    @RequestMapping(value = "/form", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    public String form(HttpSession session, SysItem model) {
        if (StrUtil.isEmpty(model.getId())) {
            model.setCreateUser(OperatorProvider.getCurrent(session).getAccount());
            int row = itemService.insert(model);
            return row > 0 ? success() : error();
        } else {
            model.setModifyUser(OperatorProvider.getCurrent(session).getAccount());
            int row = itemService.update(model);
            return row > 0 ? success() : error();
        }
    }

    /**
     * 获取字典信息
     *
     * @param primaryKey
     * @return
     */
    @RequestMapping(value = "/getForm", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    public String getForm(String primaryKey) {
        SysItem entity = itemService.get(primaryKey);
        entity.setIsEnabled(entity.getIsEnabled().equals("1") ? "true" : "false");
        return JsonUtils.toJSON(entity);
    }

    /**
     * 删除字典信息
     *
     * @param primaryKey
     * @return
     */
    @AuthorizeChecked()
    @RequestMapping(value = "/delete", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    public String delete(String primaryKey) {
        int count = itemService.getChildCount(primaryKey);
        if (count == 0) {
            // 删除字典。
            int row = itemService.delete(primaryKey);
            // 删除字典选项。
            itemService.deleteItemDetail(primaryKey);
            return row > 0 ? success() : error();
        }
        return warning("操作失败，请先删除该项的" + count + "个子级字典。");
    }

    /**
     * 字典详情画面
     *
     * @return
     */
    @AuthorizeChecked()
    @RequestMapping(value = "/detail", method = {RequestMethod.GET})
    public ModelAndView detail() {
        return new ModelAndView("system/item/detail");
    }

    /**
     * 获取字典节点
     *
     * @return
     */
    @RequestMapping(value = "/getListTree", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    public String getListTree() {
        List<SysItem> listAllItems = itemService.getItemList();
        List<ZTreeNode> result = new ArrayList<ZTreeNode>();
        for (SysItem item : listAllItems) {
            ZTreeNode model = new ZTreeNode();
            model.setId(item.getId());
            model.setpId(item.getParentId());
            model.setName(item.getName());
            model.setOpen(true);
            result.add(model);
        }
        return JsonUtils.toJSON(result);
    }

    /**
     * 获得字典信息列表
     *
     * @return
     */
    @RequestMapping(value = "/getListSelectTree", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    public String getListSelectTree() {
        List<SysItem> data = itemService.getItemList();
        List<TreeSelect> treeList = new ArrayList<TreeSelect>();
        for (SysItem item : data) {
            TreeSelect model = new TreeSelect();
            model.setId(item.getId());
            model.setText(item.getName());
            model.setParentId(item.getParentId());
            treeList.add(model);
        }
        return TreeSelectHelper.ToTreeSelectJson(treeList);
    }
}
